package thread.test_2;

public class Test2 {
    public static void main(String[] args) {
        Ticket ticket1 = new Ticket("窗口1");
        Ticket ticket2 = new Ticket("窗口2");
        ticket1.start();
        ticket2.start();
    }

    private static class Ticket extends Thread {
        public Ticket(String name) {
            super(name);
        }

        private static int ticket = 100;

        @Override
        public void run() {
            while (true) {
                String name = Thread.currentThread().getName();
                if ("窗口1".equals(name)) {
                    // 此时使用同步代码块的同时使用同步方法就会就要考虑锁对象的问题
                    synchronized (Ticket.class) {
                        if (ticket <= 0) {
                            break;
                        } else {
                            try {
                                Thread.sleep(10);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                            System.out.println(Thread.currentThread().getName() + "正在卖第" + ticket-- + "张票");
                        }
                    }
                } else {
                    boolean flag = Ticket.sellTicket();
                    if (flag) {
                        break;
                    }
                }
            }

        }

        // 同步方法
        private static synchronized boolean sellTicket() {
            if (ticket <= 0) {
                return true;
            } else {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName() + "正在卖第" + ticket-- + "张票");
                return false;
            }
        }
    }
}


